<template>
  <div class="verification-container">
    <input v-for="(code, index) in verificationCodes" :key="index" v-model="verificationCodes[index]"
      @input="handleInput(index, $event)" @keydown="handleKeyDown(index, $event)" maxlength="1"
      class="verification-input" />
  </div>
</template>

<script>
export default {
  name: 'codeInput',
  props: {
    emailCode: {
      type: Function,
      required: true
    }
  },
  data() {
    return {
      verificationCodes: ['', '', '', '', '', '']
    };
  },
  methods: {
    handleInput(index, event) {
      const value = event.target.value;
      this.$set(this.verificationCodes, index, value);

      // 判断是否输入完成
      if (this.verificationCodes.join('').length === 6) {
        this.emailCode(this.verificationCodes.join(''));
      }

      // 自动跳到下一个输入框
      if (value && index < this.verificationCodes.length - 1) {
        const nextInput = event.target.nextElementSibling;
        if (nextInput) {
          this.$nextTick(() => {
            nextInput.focus();
          });
        }
      }
    },
    handleKeyDown(index, event) {
      // 处理删除操作
      if (event.key === 'Backspace' && !event.target.value && index > 0) {
        const prevInput = event.target.previousElementSibling;
        if (prevInput) {
          this.$nextTick(() => {
            prevInput.focus();
          });
        }
      }
    }
  }
};
</script>

<style lang="less" scoped>
.verification-container {
  display: flex;
}

.verification-input {
  width: 30px;
  height: 30px;
  margin-right: 10px;
  text-align: center;
  font-size: 20px;
  border: 1px solid #766d6d;
  border-radius: 5px;

  &:last-child {
    margin-right: 0;
  }
}

.verification-input:focus {
  outline: none;

}
</style>
